package com.huluobo.lc.kotlinim1803a.ui.activity

import android.content.pm.PackageManager
import androidx.core.app.ActivityCompat
import com.huluobo.lc.kotlinim1803a.R
import com.huluobo.lc.kotlinim1803a.contract.login.LoginContract
import com.huluobo.lc.kotlinim1803a.contract.login.LoginPresenter
import kotlinx.android.synthetic.main.activity_login.*
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.toast

/**
 * @author Lc
 * @description:
 * @date :2020/9/10 19:26
 */
class LoginActivity : BaseActivity(), LoginContract.View {
    private val presenter = LoginPresenter(this)

    override fun init() {
        super.init()
        login.setOnClickListener { login() }

        password.setOnEditorActionListener { _, _, _ ->
            login()
            true
        }

        newUser.setOnClickListener { startActivity<RegisterActivity>() }

    }

    private fun login() {
        //隐藏软键盘
        hideSoftKeyboard()
        if (hasWriteExternalStoragePermission()) {
            val userNameString = userName.text.trim().toString()
            val passwordString = password.text.trim().toString()
            presenter.login(userNameString, passwordString)
        } else applyWriteExternalStoragePermission()
    }

    private fun applyWriteExternalStoragePermission() {
        //获取权限组
        val permissions = arrayOf(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
        //去请求权限
        ActivityCompat.requestPermissions(this, permissions, 0)
    }

    //权限请求的返回
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            //用户同意权限,开始登录
            login()
        } else toast(R.string.permission_denied)

    }

    private fun hasWriteExternalStoragePermission(): Boolean {
        //声明权限变量,拿到写入磁盘权限
        val checkSelfPermission = ActivityCompat.checkSelfPermission(
            this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE
        )
        //对比权限并返回,是否用户已经同意写入权限
        return checkSelfPermission == PackageManager.PERMISSION_GRANTED
    }

    override fun getLayoutResId(): Int =
        R.layout.activity_login
    override fun onUserNameError() {
        userName.error = getString(R.string.user_name_error)
    }

    override fun onPasswordError() {
        password.error = getString(R.string.password_error)
    }

    override fun onStartLogin() {
        //弹出进度条
        showProgress(getString(R.string.logging))
    }

    override fun onLoggedInSuccess() {
        //隐藏进度条
        dismissProgress()
        //进入主界面
        startActivity<MainActivity>()
        //退出当前Activity
        finish()
    }

    override fun onLoggedInFailed() {
        //隐藏进度条
        dismissProgress()
        //弹出toast
        toast(getString(R.string.login_failed))
    }
}